<template>
  <div class="add-group-member-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="添加群成员"
      left-text="返回"
      left-arrow
      @click-left="toGroupInformation();"
    />

    <!-- 搜索框 -->
    <van-search
      v-model="searchQuery"
      placeholder="搜索联系人"
      @search="onSearch"
      @clear="onSearch"
      show-action
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 联系人列表 -->
    <van-checkbox-group v-model="selectedMemberIds" ref="checkboxGroup">
      <van-cell-group>
        <van-cell
          v-for="user in filteredUsers"
          :key="user.key"
          clickable
          @click="toggleUser(user.key)"
        >
          <template #title>
            <div class="user-item">
              <van-image
                round
                width="30px"
                height="30px"
                :src="getAvatarView(user.avatar)"
                class="user-avatar"
              />
              <span class="user-name">{{ user.title }}</span>
            </div>
          </template>
          <template #right-icon>
            <van-checkbox :name="user.key" :disabled="user.disabled" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-checkbox-group>

    <!-- 底部确认按钮 -->
    <div class="submit-bar">
      <van-button
        type="primary"
        size="large"
        @click="submitAdd"
        :disabled="selectedMemberIds.length === 0"
      >
        添加（{{ selectedMemberIds.length }}）
      </van-button>
    </div>
  </div>
</template>

<script>
import { postAction, getFileAccessHttpUrl } from "@/api";
import { Toast } from 'vant';

export default {
  name: 'AddGroupMember',
  data() {
    return {
      searchQuery: '',
      allUsers: [], // 所有用户列表 [{ key, title, avatar, disabled }]
      selectedMemberIds: [], // 选中的用户 ID 列表
      groupId: '',
      navTitle: '',
    };
  },
  computed: {
    // 过滤后的用户列表（支持搜索）
    filteredUsers() {
      const q = this.searchQuery.trim().toLowerCase();
      if (!q) return this.allUsers;
      return this.allUsers.filter(user =>
        user.title.toLowerCase().includes(q)
      );
    },
  },
  async created() {
    // 从路由获取 groupId
    this.groupId = this.$route.params.groupId || this.$route.query.groupId;
    this.navTitle = this.$route.params.navTitle || this.$route.query.navTitle;
    if (!this.groupId) {
      Toast.fail('缺少群组ID');
      this.$router.back();
      return;
    }

    await this.getAllUsers();
  },
  methods: {
    toGroupInformation() {
        this.$router.push({
        name: 'groupInformation',
        params: {
            groupId: this.groupId,
            navTitle: this.navTitle
        }
        });
    },
    // 获取所有用户（排除已加入的）
    getAllUsers() {
        // 先获取所有可联系人
        postAction('/sys/chat/relative', { type: 'meeting' })
            .then(res => {
            let userList = [];
            res.result.forEach(e => {
                if (e.is_group == 0) {
                userList.push({
                    key: e.goalId,
                    title: e.displayName,
                    avatar: e.avatar,
                    disabled: false // 先默认不禁用
                });
            }
        });

            // 再请求当前群成员
            return postAction("/sys/chat/member/getGroupMember/", {
                groupId: this.groupId
            }).then(memberRes => {
                if (!memberRes.success) {
                Toast.fail(memberRes.message || '获取群成员失败');
                this.allUsers = userList;
                return;
                }

                const memberIds = Array.isArray(memberRes.result) 
                ? memberRes.result.map(m => m.memberId) 
                : [];

                // 标记已在群里的成员为 disabled
                this.allUsers = userList.map(user => ({
                ...user,
                disabled: memberIds.includes(user.key)
                }));
            });
            })
            .catch(err => {
            console.error('获取用户或群成员失败:', err);
            Toast.fail('网络错误');
        });
    },

    // 搜索
    onSearch() {
      // 过滤逻辑在 computed 中自动处理
    },

    // 切换单个用户选择状态
    toggleUser(userId) {
      const index = this.selectedMemberIds.indexOf(userId);
      if (index > -1) {
        this.selectedMemberIds.splice(index, 1);
      } else {
        // 不允许添加已禁用的用户（比如已在群里的）
        const user = this.allUsers.find(u => u.key === userId);
        if (!user.disabled) {
          this.selectedMemberIds.push(userId);
        }
      }
    },

    // 提交添加成员
    submitAdd() {
      if (this.selectedMemberIds.length === 0) {
        Toast('请至少选择一位成员');
        return;
      }

      const params = {
        groupId: this.groupId,
        memberIds: JSON.stringify(this.selectedMemberIds),
      };

      postAction('/sys/chat/member/addGroupMember', params)
        .then(res => {
          if (res.success) {
            Toast.success(`成功添加 ${this.selectedMemberIds.length} 名成员`);
            // 添加成功后，返回上一页（群信息页）
            this.toGroupInformation();
          } else {
            Toast.fail(res.message || '添加失败');
          }
        })
        .catch(err => {
          console.error('添加成员请求失败:', err);
          Toast.fail('网络错误，添加失败');
        });
    },

    // 获取头像地址
    getAvatarView(avatar) {
      return avatar ? getFileAccessHttpUrl(avatar) : '/static/mobile/img/common/user_default.webp';
    },
  },
};
</script>

<style scoped>
.add-group-member-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px; /* 给底部按钮留空间 */
}

/* 用户项样式 */
.user-item {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 10px;
}

.user-name {
  font-size: 14px;
  color: #323233;
}

/* 搜索框 */
.van-search {
  padding: 5px 10px;
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
}

/* 提交栏 */
.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 92%;
  background-color: #fff;
  padding: 8px 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
</style>